<template>
	<view class="category-manage">
		<!-- 分类面板 -->
		<view class="category-panel11" :class="{ 'show-secondary': showSecondary }">
			<!-- 一级分类列表 -->
			<view class="primary-panel">
				<view class="panel-header">
					<text class="title">商品分类</text>
					<view class="header-right">
						<input class="search-input" type="text" v-model="firstLevelKeyword" placeholder="搜索分类" />
					</view>
				</view>
				<scroll-view class="panel-content" :scroll-y="true" :style="{ height: scrollHeight + 'px' }">
					<view
						v-for="item in filteredFirstLevelCategories"
						:key="item.id"
						class="category-item"
						:class="{ active: currentCategory?.id === item.id }"
						@click="handleCategoryClick(item)"
					>
						<image class="category-icon" :src="item.picUrl || defaultIcon" mode="aspectFill" />
						<view class="category-info">
							<view class="category-main">
								<text class="category-name">{{ item.name }}</text>
								<text class="sub-count">({{ getSubCategoryCount(item.id) }})</text>
							</view>
						</view>
						<view class="category-actions">
							<uni-icons type="right" size="16"></uni-icons>
						</view>
					</view>
					<view v-if="filteredFirstLevelCategories.length === 0" class="empty-tip"> 暂无数据 </view>
				</scroll-view>
			</view>

			<!-- 二级分类列表 -->
			<view class="secondary-panel" :class="{ show: showSecondary }">
				<view class="panel-header">
					<view class="header-left">
						<button class="back-btn" size="mini" @click="handleBack">
							<text class="back-icon">←</text>
							返回
						</button>
						<text class="title">{{ currentCategoryName }}的子分类</text>
					</view>
					<view class="header-right">
						<input class="search-input" type="text" v-model="secondLevelKeyword" placeholder="搜索子分类" />
						<button type="primary" size="mini" @click="handleAddCategory(true)">添加子分类</button>
					</view>
				</view>
				<scroll-view class="panel-content" :scroll-y="true" :style="{ height: scrollHeight + 'px' }">
					<view v-for="item in filteredSecondLevelCategories" :key="item.id" class="category-item">
						<image class="category-icon" :src="item.picUrl || defaultIcon" mode="aspectFill" />
						<view class="category-info">
							<view class="category-main">
								<text class="category-name">{{ item.name }}</text>
								<text class="category-status" :class="{ 'status-disabled': item.status === 0 }">
									{{ item.status === 1 ? '已启用' : '已禁用' }}
								</text>
							</view>
							<text class="category-sort">排序: {{ item.sort || 0 }}</text>
						</view>
						<view class="category-actions">
							<button class="status-btn" :class="{ 'status-disabled': item.status === 0 }" size="mini" @click.stop="handleStatusChange(item)">
								{{ item.status === 1 ? '禁用' : '启用' }}
							</button>
							<button class="edit-btn" size="mini" @click.stop="handleEditCategory(item)">编辑</button>
							<button class="delete-btn" size="mini" @click.stop="handleDeleteCategory(item)">删除</button>
						</view>
					</view>
					<view v-if="filteredSecondLevelCategories.length === 0" class="empty-tip"> 暂无子分类数据 </view>
				</scroll-view>
			</view>
		</view>

		<!-- 编辑分类弹窗 -->
		<view v-if="showEditModal" class="modal-mask" @click="closeEditModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{ isEdit ? '编辑' : '添加' }}{{ editForm.parentId ? '子' : '' }}分类</text>
					<text class="modal-close" @click="closeEditModal">×</text>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="label">分类名称</text>
						<input class="input" type="text" v-model="editForm.name" placeholder="请输入分类名称" />
					</view>
					<view class="form-item">
						<text class="label">分类图标</text>
						<view class="upload-area" @click="handleChooseImage">
							<image v-if="editForm.picUrl" class="preview-image" :src="editForm.picUrl" mode="aspectFill" />
							<view v-else class="upload-placeholder">
								<text class="upload-icon">+</text>
								<text class="upload-text">上传图标</text>
							</view>
						</view>
					</view>
					<view class="form-item">
						<text class="label">排序号</text>
						<input class="input" type="number" v-model="editForm.sort" placeholder="请输入排序号" />
					</view>
					<view v-if="editForm.parentId" class="form-item">
						<text class="label">所属分类</text>
						<text class="parent-category">{{ currentCategoryName }}</text>
					</view>
					<view class="form-item">
						<text class="label">状态</text>
						<radio-group class="status-group" v-model="editForm.status">
							<label class="status-label"> <radio :value="1" :checked="editForm.status === 1" />启用 </label>
							<label class="status-label"> <radio :value="0" :checked="editForm.status === 0" />禁用 </label>
						</radio-group>
					</view>
				</view>
				<view class="modal-footer">
					<button @click="closeEditModal">取消</button>
					<button type="primary" @click="handleSaveCategory">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watchEffect } from 'vue';
import { getCategoryList, createCategory, updateCategory, deleteCategory, uploadCategoryImage } from '@/api/product/category';

interface CategoryVO {
	id: number;
	parentId?: number;
	name: string;
	picUrl: string;
	sort?: number;
	status?: number;
}

// 响应式数据
const firstLevelCategories = ref<CategoryVO[]>([]);
const secondLevelCategories = ref<CategoryVO[]>([]);
const loading = ref(false);

const currentCategory = ref<CategoryVO | null>(null);
// UI状态
const showSecondary = ref(false);
const showEditModal = ref(false);
const isEdit = ref(false);

// 页面数据
const scrollHeight = ref(500);
const firstLevelKeyword = ref('');
const secondLevelKeyword = ref('');
const defaultIcon = '/static/images/default-category-icon.png';

// 计算属性

// 确保页面加载时显示一级分类
onMounted(() => {
	showSecondary.value = false;
	initScrollHeight();

	// 加载一级分类数据
	loadFirstLevelCategories();

	// 监听窗口大小变化，更新滚动区域高度
	window.addEventListener('resize', initScrollHeight);
});

// 加载一级分类数据
const loadFirstLevelCategories = async () => {
	loading.value = true;
	try {
		const res = await getCategoryList({ parentId: 0 });
		if (res.code === 0 && res.data) {
			console.log('一级分类数据:', res.data);
			firstLevelCategories.value = res.data;
			currentCategory.value = res.data[0];
			await nextTick(); // 等待DOM更新
		} else {
			uni.showToast({
				title: res.msg || '加载分类失败',
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('加载一级分类失败:', error);
		uni.showToast({
			title: '加载分类失败',
			icon: 'none',
		});
	} finally {
		loading.value = false;
	}
};

// 加载二级分类数据
const loadSecondLevelCategories = async (parentId: number) => {
	loading.value = true;
	try {
		const res = await getCategoryList({ parentId });
		if (res.code === 0 && res.data) {
			secondLevelCategories.value = res.data;
		} else {
			uni.showToast({
				title: res.msg || '加载子分类失败',
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('加载二级分类失败:', error);
		uni.showToast({
			title: '加载子分类失败',
			icon: 'none',
		});
	} finally {
		loading.value = false;
	}
};

// 编辑表单数据
const editForm = ref<{
	id?: number;
	parentId?: number;
	name: string;
	picUrl: string;
	sort: number;
	status: number;
}>({
	name: '',
	picUrl: '',
	sort: 0,
	status: 1,
});
// 过滤后的一级分类列表
const filteredFirstLevelCategories = computed(() => {
	console.log('分类:', firstLevelCategories.value);
	if (!firstLevelKeyword.value) return firstLevelCategories.value;
	const keyword = firstLevelKeyword.value.toLowerCase().trim();
	console.log('过滤后的分类:', firstLevelCategories);
	return firstLevelCategories.value.filter((category) => category.name.toLowerCase().includes(keyword));
});

// 过滤后的二级分类列表
const filteredSecondLevelCategories = computed(() => {
	if (!currentCategory.value) return [];

	let filtered = secondLevelCategories.value.filter((item) => item.parentId === currentCategory.value?.id);

	if (secondLevelKeyword.value) {
		const keyword = secondLevelKeyword.value.toLowerCase().trim();
		filtered = filtered.filter((item) => item.name.toLowerCase().includes(keyword));
	}

	// 按sort字段排序
	return filtered.sort((a, b) => (a.sort || 0) - (b.sort || 0));
});

const currentCategoryName = computed(() => {
	return currentCategory.value?.name || '请选择分类';
});

// 方法
const getSubCategoryCount = (parentId: number) => {
	return secondLevelCategories.value.filter((item) => item.parentId === parentId).length;
};

// 处理一级分类点击
const handleCategoryClick = (category: CategoryVO) => {
	currentCategory.value = category;
	secondLevelKeyword.value = '';
	showSecondary.value = true;

	// 加载该分类下的二级分类
	loadSecondLevelCategories(category.id);
};

// 返回一级分类列表
const handleBack = () => {
	showSecondary.value = false;
	currentCategory.value = null;
	secondLevelKeyword.value = '';
};

// 重置搜索
const resetSearch = () => {
	firstLevelKeyword.value = '';
	secondLevelKeyword.value = '';
};

// 状态变更（仅用于二级分类）
const handleStatusChange = async (category: CategoryVO) => {
	if (!category.parentId) return; // 忽略一级分类的状态变更

	try {
		loading.value = true;
		const newStatus = category.status === 1 ? 0 : 1;
		const res = await updateCategory({
			id: category.id,
			status: newStatus,
		});

		if (res.code === 0) {
			// 更新本地数据
			const index = secondLevelCategories.value.findIndex((item) => item.id === category.id);
			if (index !== -1) {
				secondLevelCategories.value[index].status = newStatus;
			}

			uni.showToast({
				title: '状态更新成功',
				icon: 'success',
			});
		} else {
			uni.showToast({
				title: res.msg || '状态更新失败',
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('更新分类状态失败:', error);
		uni.showToast({
			title: '状态更新失败',
			icon: 'error',
		});
	} finally {
		loading.value = false;
	}
};

// 添加分类（仅添加二级分类）
const handleAddCategory = (isSecondLevel: boolean = false) => {
	if (!isSecondLevel) return; // 不允许添加一级分类

	isEdit.value = false;
	editForm.value = {
		name: '',
		picUrl: defaultIcon,
		sort: filteredSecondLevelCategories.value.length + 1,
		status: 1,
	};

	if (!currentCategory.value) {
		uni.showToast({
			title: '请先选择上级分类',
			icon: 'none',
		});
		return;
	}

	editForm.value.parentId = currentCategory.value.id;
	showEditModal.value = true;
};

// 编辑分类（仅编辑二级分类）
const handleEditCategory = (category: CategoryVO) => {
	if (!category.parentId) return; // 不允许编辑一级分类

	isEdit.value = true;
	editForm.value = {
		id: category.id,
		parentId: category.parentId,
		name: category.name,
		picUrl: category.picUrl || defaultIcon,
		sort: category.sort || 0,
		status: category.status || 1,
	};
	showEditModal.value = true;
};

// 删除分类（仅删除二级分类）
const handleDeleteCategory = async (category: CategoryVO) => {
	if (!category.parentId) return; // 不允许删除一级分类

	try {
		const [err, res] = await uni.showModal({
			title: '确认删除',
			content: `确定要删除子分类"${category.name}"吗？`,
			confirmText: '删除',
			confirmColor: '#ff4d4f',
		});

		if (err || !res.confirm) return;

		loading.value = true;
		const apiRes = await deleteCategory(category.id);

		if (apiRes.code === 0) {
			// 更新本地数据
			secondLevelCategories.value = secondLevelCategories.value.filter((item) => item.id !== category.id);

			uni.showToast({
				title: '删除成功',
				icon: 'success',
			});
		} else {
			uni.showToast({
				title: apiRes.msg || '删除失败',
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('删除分类失败:', error);
		uni.showToast({
			title: '删除失败',
			icon: 'error',
		});
	} finally {
		loading.value = false;
	}
};

const handleChooseImage = async () => {
	try {
		const [err, res] = await uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
		});

		if (err || !res.tempFilePaths?.length) {
			throw new Error('选择图片失败');
		}

		loading.value = true;
		const tempFilePath = res.tempFilePaths[0];

		// 上传图片到服务器
		const uploadRes = await uploadCategoryImage({
			filePath: tempFilePath,
			name: 'file',
		});

		if (uploadRes.code === 0 && uploadRes.data) {
			editForm.value.picUrl = uploadRes.data.url;
			uni.showToast({
				title: '图片上传成功',
				icon: 'success',
			});
		} else {
			uni.showToast({
				title: uploadRes.msg || '图片上传失败',
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('选择或上传图片失败:', error);
		uni.showToast({
			title: '图片上传失败',
			icon: 'none',
		});
	} finally {
		loading.value = false;
	}
};

const validateForm = () => {
	if (!editForm.value.name.trim()) {
		uni.showToast({
			title: '请输入分类名称',
			icon: 'none',
		});
		return false;
	}

	if (!editForm.value.picUrl) {
		uni.showToast({
			title: '请上传分类图标',
			icon: 'none',
		});
		return false;
	}

	if (editForm.value.sort < 0) {
		uni.showToast({
			title: '排序号必须大于等于0',
			icon: 'none',
		});
		return false;
	}

	return true;
};

const handleSaveCategory = async () => {
	if (!validateForm()) return;

	try {
		loading.value = true;
		const categoryData = { ...editForm.value };

		let res;
		if (isEdit.value) {
			// 更新现有分类
			res = await updateCategory(categoryData);
		} else {
			// 添加新分类
			res = await createCategory(categoryData);
		}

		if (res.code === 0) {
			// 重新加载分类数据以确保数据同步
			if (categoryData.parentId) {
				await loadSecondLevelCategories(categoryData.parentId);
			} else {
				await loadFirstLevelCategories();
			}

			uni.showToast({
				title: isEdit.value ? '更新成功' : '添加成功',
				icon: 'success',
			});

			closeEditModal();
		} else {
			uni.showToast({
				title: res.msg || (isEdit.value ? '更新失败' : '添加失败'),
				icon: 'none',
			});
		}
	} catch (error) {
		console.error('保存分类失败:', error);
		uni.showToast({
			title: isEdit.value ? '更新失败' : '添加失败',
			icon: 'error',
		});
	} finally {
		loading.value = false;
	}
};

const closeEditModal = () => {
	showEditModal.value = false;
	editForm.value = {
		name: '',
		picUrl: defaultIcon,
		sort: 0,
		status: 1,
	};
};

// 计算页面滚动区域高度
const initScrollHeight = () => {
	const info = uni.getSystemInfoSync();
	// 减去顶部导航栏高度和底部安全区域高度
	scrollHeight.value = info.windowHeight - 44 - (info.safeAreaInsets?.bottom || 0);
	console.log('计算的高度:', scrollHeight.value);
};

// 生命周期钩子已在前面定义，这里删除重复的部分

// 组件卸载时清理事件监听
onUnmounted(() => {
	window.removeEventListener('resize', initScrollHeight);
});
</script>

<style lang="scss" scoped>
.category-manage {
	height: 100%;
	background-color: #f5f5f5;
	padding: 20rpx;
	box-sizing: border-box;

	.category-panel {
		height: 100%;
		background-color: #fff;
		border-radius: 8rpx;
		overflow: hidden;
		position: relative;

		.primary-panel,
		.secondary-panel {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: #fff;
			transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
			display: flex;
			flex-direction: column;
			backface-visibility: hidden;
			will-change: transform;
		}

		.primary-panel {
			transform: translateX(0);
			z-index: 2;

			.category-item {
				cursor: pointer;

				&:hover {
					background-color: #f5f5f5;
				}

				&.active {
					background-color: #e6f7ff;
				}
			}
		}

		.secondary-panel {
			transform: translateX(100%);
			z-index: 1;
		}

		&.show-secondary {
			.primary-panel {
				transform: translateX(-100%);
			}

			.secondary-panel {
				transform: translateX(0);
			}
		}
	}

	.header-left {
		display: flex;
		align-items: center;
		gap: 20rpx;

		.back-btn {
			display: flex;
			align-items: center;
			gap: 4rpx;
			margin: 0;
			padding: 0 20rpx;

			.back-icon {
				font-size: 32rpx;
			}
		}
	}

	.panel-header {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
		// display: flex;
		// justify-content: space-between;
		// align-items: center;
		display: flex;
  		flex-wrap: wrap; /* 允许元素换行 */
  		gap: 16px; /* 设置元素间距 */
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.header-right {
			display: flex;
			align-items: center;
			gap: 20rpx;

			.search-input {
				width: 300rpx;
				height: 60rpx;
				padding: 0 20rpx;
				border: 1px solid #ddd;
				border-radius: 4rpx;
				font-size: 28rpx;
			}
		}
	}

	.panel-content {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto; /* 确保可以滚动 */
		background-color: #b1b1a3; /* 确保背景可见 */

		.category-item {
			display: flex;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1px solid #5022c4;
			transition: all 0.3s;

			&:last-child {
				border-bottom: none;
			}

			&.active {
				background-color: #e6f7ff;
			}

			.category-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}

			.category-info {
				flex: 1;

				.category-main {
					display: flex;
					align-items: center;
					gap: 8rpx;
					margin-bottom: 4rpx;

					.category-name {
						font-size: 28rpx;
						color: #333;
					}

					.sub-count {
						font-size: 24rpx;
						color: #999;
					}

					.category-status {
						font-size: 24rpx;
						padding: 2rpx 10rpx;
						border-radius: 10rpx;
						background-color: #52c41a;
						color: #fff;

						&.status-disabled {
							background-color: #ff4d4f;
						}
					}
				}

				.category-sort {
					font-size: 24rpx;
					color: #999;
				}
			}

			.category-actions {
				display: flex;
				align-items: center;

				// 一级分类的箭头图标
				.uni-icons {
					color: #999;
				}

				// 二级分类的操作按钮
				button {
					margin: 0 0 0 10rpx;

					&.status-btn {
						background-color: #52c41a;
						color: #fff;

						&.status-disabled {
							background-color: #ff4d4f;
						}
					}

					&.edit-btn {
						background-color: #1890ff;
						color: #fff;
					}

					&.delete-btn {
						background-color: #ff4d4f;
						color: #fff;
					}
				}
			}
		}

		.empty-tip {
			text-align: center;
			color: #999;
			padding: 40rpx 0;
		}
	}
}

.modal-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;

	.modal-content {
		width: 600rpx;
		background-color: #fff;
		border-radius: 8rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);

		.modal-header {
			padding: 20rpx;
			border-bottom: 1px solid #eee;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.modal-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.modal-close {
				font-size: 40rpx;
				color: #999;
				cursor: pointer;
				padding: 10rpx;

				&:hover {
					color: #666;
				}
			}
		}

		.modal-body {
			padding: 30rpx;

			.form-item {
				margin-bottom: 30rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					display: block;
					margin-bottom: 10rpx;
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}

				.input {
					width: 100%;
					height: 80rpx;
					padding: 0 20rpx;
					border: 1px solid #ddd;
					border-radius: 4rpx;
					font-size: 28rpx;
					box-sizing: border-box;
					transition: all 0.3s;

					&:focus {
						border-color: #1890ff;
						box-shadow: 0 0 0 2rpx rgba(24, 144, 255, 0.2);
					}
				}

				.upload-area {
					width: 200rpx;
					height: 200rpx;
					border: 1px dashed #ddd;
					border-radius: 4rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					cursor: pointer;
					transition: all 0.3s;

					&:hover {
						border-color: #1890ff;
					}

					.preview-image {
						width: 100%;
						height: 100%;
						border-radius: 4rpx;
					}

					.upload-placeholder {
						text-align: center;
						color: #999;

						.upload-icon {
							font-size: 48rpx;
							margin-bottom: 10rpx;
						}

						.upload-text {
							font-size: 24rpx;
						}
					}
				}

				.parent-category {
					font-size: 28rpx;
					color: #666;
					padding: 20rpx;
					background-color: #f5f5f5;
					border-radius: 4rpx;
				}

				.status-group {
					display: flex;
					gap: 40rpx;

					.status-label {
						font-size: 28rpx;
						color: #333;
						display: flex;
						align-items: center;
						gap: 8rpx;
					}
				}
			}
		}

		.modal-footer {
			padding: 20rpx 30rpx;
			border-top: 1px solid #eee;
			display: flex;
			justify-content: flex-end;
			gap: 20rpx;

			button {
				margin: 0;
				min-width: 160rpx;
				height: 72rpx;
				line-height: 72rpx;
				font-size: 28rpx;

				&[type='primary'] {
					background-color: #1890ff;

					&:active {
						background-color: #096dd9;
					}
				}
			}
		}
	}
}
</style>
